Skip to content

Conversation

@DaniilPavlov
Copy link

@DaniilPavlov DaniilPavlov commented Feb 19, 2018

Долго пытался подвести все под двоичную систему, но в итоге ни к чему хорошему это так и не привело.Также до сих пор не смог сделать деление столбиком, просто сижу залипаю в экран, что-то пишу и через пару часов эти несчастные 10-20 строчек стираю.

@h31 h31 changed the title Даниил Павлов, BigInteger Даниил Павлов, Беззнаковое большое целое число Feb 19, 2018

class BigBigInt {

private String value;//Хранимое значение исходного огромного числа (bbInt)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Есть более эффективные способы хранить число. char - это два байта, в каждом char помещается только одна цифра числа.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вообще, замечание такое же, как и к Сергею - абстрагируйтесь от конкретного типа хранилища данных. То есть ваша бизнес-логика (код, который решает поставленную задачу) не должна знать, как именно вы храните число. Сделайте набор методов по работе с хранилищем (получить i-ую часть числа и т.д.), и пусть логика работает только с этими методами.


private String value;//Хранимое значение исходного огромного числа (bbInt)

String getValue() {//Получение значения bbInt
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

toString тогда уж

//Обработка впередиидущих '0' и ' '
int i;
for (i = 0; i < string.length(); i++) {
if (string.charAt(i) != '0' && string.charAt(i) != ' ') {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Похожую обработку делает метод String.replaceFirst. Но ваш вариант имеет свои преимущества (меньшее потребление памяти), так что можно оставить его.

if (string.charAt(i) != '0' && string.charAt(i) != ' ') {
break;
}
if (i == string.length() - 1 && string.charAt(i) == '0') {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не обязательно проверять это внутри цикла. Можно проверит и после его окончания (в таком случае условие становится даже немного проще).

return value;
}

BigBigInt(String string) { //Конструктор класса
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Называйте имена переменных и аргументов так, чтобы название соответствовало содержимому и описывало его. string почти ничего не говорит о том, что содержит переменная.

string.getChars(i, string.length(), help, 0);
value = new String(help);
//Обработка ввода строки не содержащей чисел
if (value.compareTo("") == 0) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

equals

//Преобразование строик в число без впередиидущих '0' и ' '
char[] help = new char[string.length() - i];
string.getChars(i, string.length(), help, 0);
value = new String(help);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

String.substring

}
}

int Comparison(BigBigInt bbInt) {//Сравнение двух bbInt
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Методы называются со строчной буквы (см. camelCase)

int Comparison(BigBigInt bbInt) {//Сравнение двух bbInt
int result = -2;
if (this.value.compareTo(bbInt.value) == 0) {
result = 0;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем нужна переменная result? Почему бы сразу не возвращать нужное значение?


static BigBigInt addition(BigBigInt bbInt1, BigBigInt bbInt2) {//Сумма двух bbInt
if (bbInt1.Comparison(bbInt2) < 0) {
BigBigInt bbInt;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Другой вариант - сделать return addition(bbInt2, bbInt1)

return result;
}

static BigBigInt addition(BigBigInt bbInt1, BigBigInt bbInt2) {//Сумма двух bbInt
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему метод static?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кроме того, в именах методов обычно используются глаголы, т.е. например add.

String answer = "";
String str2 = "";
for (int i = 0; i < bbInt1.value.length() - bbInt2.value.length(); i++) {
str2 = str2 + "0";
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

StringBuilder

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кроме того, в случае сложения/вычитания заранее можно рассчитать максимальное количество разрядов. То есть даже без StringBuilder можно обойтись, если использовать массивы.

return new BigBigInt(answer);
}

static BigBigInt subtraction(BigBigInt bbInt1, BigBigInt bbInt2) {//Разность двух bbInt
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Код очень похож на addition. Можно ли как-нибудь устранить дублирование?


static BigBigInt subtraction(BigBigInt bbInt1, BigBigInt bbInt2) {//Разность двух bbInt
if (bbInt1.Comparison(bbInt2) < 0) {
BigBigInt bbInt;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно объявить переменную и в той же строчке задать ей значение

String ans = "";
for (int j = bbInt1.value.length() - 1; j >= 0; j--) {
help += Integer.parseInt(bbInt2.value.charAt(i) + "") * Integer.parseInt(bbInt1.value.charAt(j) + "");
ans = (help % 10) + ans;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

StringBuilder

return new BigBigInt(counter);
}

static BigBigInt residue(BigBigInt bbInt1, BigBigInt bbInt2) {//Остаток от деления двух bbInt
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Арифметический остаток переводится как remainder.

do {
str2 = addition(bbInt, bbInt2).value;
bbInt = new BigBigInt(str2);
counter = addition(new BigBigInt(counter), new BigBigInt("1")).value;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Очень неэффективный способ деления. По сути - перебор. Нужно придумать что-нибудь эффективнее.

@h31 h31 added good Хорошо penalty Оценка с минусом labels Mar 13, 2018
@h31
Copy link
Owner

h31 commented Mar 15, 2018

Помечаю задачу как завершенную. Если захотите, чтобы я прокомментировал код и дал какие-нибудь советы (без пересчета оценки, просто для собственного понимания задачи и приобретения опыта) - пишите.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

good Хорошо penalty Оценка с минусом

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants